const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')

const index = require('./routes/index')
const yiXianTong = require('./routes/yiXianTong')

// error handler
onerror(app)

//相关资料：https://www.weipxiu.com/4019.html
//跨域
app.use(cors());//设置允许所有域名跨域访问
// app.use(cors({
//   origin: function (ctx) {
//       const whiteList = ['http://localhost:8080','http://localhost:8081']; //可跨域白名单
//       let url = ctx.header.referer.substr(0,ctx.header.referer.length - 1);
      
//       if(whiteList.includes(url)){
//           return url //注意，这里域名末尾不能带/，否则不成功，所以在之前我把/通过substr干掉了
//       }
//   }
// }));

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(yiXianTong.routes(), yiXianTong.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
